<?php

namespace App\Http\Controllers;

use App\Http\Requests\CashflowRequest;
use App\Imports\CashflowImport;
use App\Models\Cashbook;
use App\Models\Cashflow as Model;
use App\Models\Cashflow;
use Carbon\Carbon;
use Iamxcd\LaravelCRUD\Traits\HasCrud;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class CashflowController extends Controller
{
    use HasCrud;

    public function __construct(Model $model)
    {
        $this->model = $model;
        $this->request = app(CashflowRequest::class);
    }

    /**
     * 新增账单
     */
    public function appStore()
    {
        $request = $this->request;
        $data = $request->validated();

        $date = Carbon::parse($data['date']);

        $data['year'] = $date->year;
        $data['month'] = $date->month;
        $data['day'] = $date->day;
        $data['user_id'] = Auth::id();

        $this->model->create($data);
        return $this->responseMessage('创建成功');
    }

    public function appUpdate()
    {
        $request = $this->request;
        $data = $request->validated();

        $model = $this->model::query()->where('user_id', Auth::id())->find($data['id']);
        if (is_null($model)) {
            return $this->responseError('记录不存在');
        }

        $date = Carbon::parse($data['date']);

        $data['year'] = $date->year;
        $data['month'] = $date->month;
        $data['day'] = $date->day;
        $data['user_id'] = Auth::id();

        $model->update($data);

        return $this->responseMessage('更新成功');
    }

    /**
     * 每月收支列表
     */
    public function appList()
    {
        $request = $this->request;
        $data = $request->validated();

        Cashflow::cashbookCheck(Auth::id(), $data['cashbook_id']);

        $_list = $this->model::query()
            ->where('user_id', Auth::id())
            ->where('cashbook_id', $data['cashbook_id'])
            ->where('year', $data['year'])
            ->where('month', $data['month'])
            ->with('category:id,name,icon')
            ->get();

        $in_amount = $_list->where('type', Cashflow::TYPE_IN)->sum('amount');
        $out_amount = $_list->where('type', Cashflow::TYPE_OUT)->sum('amount');

        $list = [];

        $days = $_list->groupBy('day');
        foreach ($days as $day) {
            $date =  Carbon::parse($day->first()->date);

            $list[] = [
                'in' => number_format($day->where('type', Cashflow::TYPE_IN)->sum('amount'), 2, '.', ''),
                'out' => number_format($day->where('type', Cashflow::TYPE_OUT)->sum('amount'), 2, '.', ''),
                'list' => $day,
                'time' => $date->month . '月' . $date->day . '日',
                'week' =>  $this->weekCn($date->dayOfWeek),
            ];
        }

        return $this->response([
            'list' => $list,
            'in' => number_format($in_amount, 2, '.', ''),
            'out' => number_format($out_amount, 2, '.', '')
        ], '获取成功');
    }

    private function weekCn($val)
    {
        switch ($val) {
            case 0:
                return '周日';
                break;
            case 1:
                return '周一';
                break;
            case 2:
                return '周二';
                break;
            case 3:
                return '周三';
                break;
            case 4:
                return '周四';
                break;
            case 5:
                return '周五';
                break;
            case 6:
                return '周六';
                break;
            default:
                break;
        }
        return '';
    }

    // 账单详情
    public function appShow($id)
    {
        $model = $this->model::query()
            ->with('category:id,name')
            ->where('user_id', Auth::id())
            ->find($id, [
                'id',
                'amount',
                'date',
                'category_id',
                'image',
                'remark',
                'date',
                'type'
            ]);

        if (is_null($model)) {
            return $this->responseError('记录不存在');
        }
        return $this->response($model, '获取成功');
    }

    /**
     * 用户删除记录
     */
    public function appDestroy($id)
    {
        $this->model::query()->where('id', $id)->where('user_id', Auth::id())->delete();
        return $this->responseMessage('删除成功');
    }

    /**
     * 导入流水信息
     */
    public function import()
    {
        $request = $this->request;
        $data = $request->validated();
        Excel::import(new CashflowImport($data['user_id']), $data['file_path'], 'public');
        return $this->responseMessage('导入成功');
    }
}
